// import vue from 'vue';
import Network from '@/lib/network';
import { globalStore } from '@/store';
class serviceController {
  constructor() {
    this.requestHttp = [];
    this.httpNum = 'http';
    this._httpIndex = 0;
    // 加载loading 封装
    this.openLoading = () => {
      if (!this.requestHttp.length) {
        uni.showLoading({ mask: true });
      }
      this._httpIndex += 1;
      this.requestHttp.push(this.httpNum);
    };

    // 清除loading
    this.clearLoading = async (isLoading) => {
      if (this.requestHttp.length === this._httpIndex && !isLoading) {
        uni.hideLoading();
        this._httpIndex = 0;
        this.requestHttp = [];
      }
    };
  }
  // 无网络状态
  goNetwork(isLoading, networkType, isToast) {
    this.clearLoading(isLoading);
    uni.hideLoading();
    if (isToast) {
      uni.$u.toast('网络连接超时，请检查后重试');
    }
    uni.setStorageSync('networkType', networkType);
  }
  // 请求封装
  service(options) {
    var _this = this;
    const gStore = globalStore();
    return new Promise(async (resolve, reject) => {
      let networkType = await Network();
      var isLoading = options.isLoading || false;
      var isNetwork = options.isNetwork || options.method === 'post';
      var _token = gStore.token; //  "ce101b8e8986a73a35d01e0305545e83"
      // 删除Loading参数
      if (options.isLoading) {
        delete options.isLoading;
      }
      if (options.token) {
        _token = options.token;
      }
      // 加载loading
      if (!isLoading) {
        _this.openLoading();
      }
      var _headers = {
        'content-type': 'application/json',
      };
      if (_token || options.token) {
        _headers.token = _token || options.token;
      }
      var _networkType = uni.getStorageSync('networkType');
      if (networkType === 'none' && uni.$u.test.isEmpty(_networkType)) {
        this.goNetwork(isLoading, _networkType, isNetwork);
      }
      // 有网的时候删除标识
      if (networkType !== 'none') {
        uni.removeStorageSync('networkType');
      }
      var optionsData = {
        ...options,
      };
      uni.request({
        url: uni.$serverUrl + optionsData.url,
        header: optionsData.header || _headers,
        data: optionsData.data,
        method: optionsData.method || 'get',
        timeout: optionsData.timeout || 60000,
        success: (response) => {
          var message = '';
          var _data = response && response.data;
          if (_data) {
            if (_data.code !== 200 && _data.status !== 200) {
              if (response.statusCode === 404) {
                message = 'Error: 404';
              }
              if (
                _data.code === 500 ||
                response.statusCode === 500 ||
                response.statusCode === 502
              ) {
                message = '网络连接超时，请检查后重试';
              }
              reject(response.data);
              _this.clearLoading(isLoading);
              !optionsData.isToast &&
                uni.$u.toast(message || _data.error || _data.message);
            } else {
              resolve(_data.data);
            }
          } else {
            reject('err');
          }
          // 判断所有请求在第一个请求和最后一个请求时关闭
          _this.clearLoading(isLoading);
        },
        fail: (error) => {
          console.log('error', error);
          _this.clearLoading(isLoading);
          reject(error);
        },
      });
    });
  }
}

export default new serviceController();
